//蛇对象

//属性: 宽高 、 蛇头背景色、 蛇身背景色、 蛇头蛇身蛇尾坐标位置x y
function Snake(options) {
    options = options || {};
    this.width = options.width || 20;
    this.height = options.height || 20;
    this.direction = options.direction || 'right';
    this.headBgc = options.headBgc || 'red';
    this.bodyBgc = options.bodyBgc || 'green';
    this.body = [{
        x: 2,
        y: 0
    }, {
        x: 1,
        y: 0
    }, {
        x: 0,
        y: 0
    }];
}
//方法: 
// 1. 蛇需要渲染到页面中
Snake.prototype.render = function(target) {
    for (var i = 0; i < this.body.length; i++) {
        var span = document.createElement('span');
        span.style.width = this.width + 'px';
        span.style.height = this.height + 'px';
        if (i == 0) {
            span.style.backgroundColor = this.headBgc;
        } else {
            span.style.backgroundColor = this.bodyBgc;
        }
        span.style.position = 'absolute';
        span.style.left = this.body[i].x * this.width + 'px';
        span.style.top = this.body[i].y * this.height + 'px';
        target.appendChild(span);
    }
};
// 2. 蛇移动
Snake.prototype.move = function(target, food) {
    var newHead = {
        x: this.body[0].x,
        y: this.body[0].y
    }
    switch (this.direction) {
        case 'right':
            newHead.x++;
            break;
        case 'left':
            newHead.x--;
            break;
        case 'up':
            newHead.y--;
            break;
        case 'down':
            newHead.y++;
            break;
    }
    if (newHead.x == food.x && newHead.y == food.y) {
        var div = target.querySelector('div');
        target.removeChild(div);
        food.render(target);
    } else {
        this.body.pop();
    }
    this.body.unshift(newHead);
    var spans = document.querySelectorAll('span');
    for (var i = 0; i < spans.length; i++) {
        target.removeChild(spans[i]);
    }
    this.render(target);
};